<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-11-12 11:26:45
 * @Last Modified time: 2022-12-07 16:35:09
 */
namespace app\common\services\system;

use frank\base\BaseService;
use frank\utils\helper\ArrayHelper;
use app\common\dao\system\ConfigTabDao;
use frank\exception\CommonException;

/**
 * 系统配置分类
 * Class ConfigTabService
 */
class ConfigTabService extends BaseService
{
	/**
     * ConfigTabService constructor.
     * @param ConfigTabDao $dao
     */
    public function __construct(ConfigTabDao $dao)
    {
        $this->dao = $dao;
    }
    
    public function getConfigTabDetail($filter)
    {
        $detail = $this->dao->detail($filter);
        if (!$detail) {
            throw new CommonException('数据不存在');
        }
        return $detail->toArray();
    }

    /**
     * 获取配置分类列表
     */
    public function getConfigTabList(array $where)
    {
        [$page, $limit] = $this->getPageValue();
        $list = $this->dao->getConfigTabList($where, $page, $limit);
        $count = $this->dao->count($where);
        $childrenValue = [];
        $list = ArrayHelper::getArrayTreeChildren($list);
        return compact('list', 'count');
    }

    /**
     * 获取配置分类选择下拉树
     */
    public function getSelectTree($pid = 0)
    {
        $menuList = $this->dao->getConfigTabAll([], ['id', 'pid', 'title']);
        $list = ArrayHelper::sortListTier($menuList, 0, 'pid', 'id');
        $menus = [['value' => 0, 'label' => '顶级按钮']];
        foreach ($list as $menu) {
            $arr = ['value' => $menu['id'], 'label' => $menu['html'] . $menu['title']];
            if($pid && $pid == $menu['id']){
                $arr['disabled'] = true;
            }
            $menus[] = $arr;
        }
        return $menus;
    }

    public function getConfigByEngField($field){
        $detail = $this->getConfigTabDetail(['eng_field'=>$field]);
        $list = $this->dao->getConfigTabSelect(['pid'=>$detail['id']]);
        foreach ($list as $key => &$item) {
            $item['children'] = $this->dao->getConfigTabSelect(['pid'=>$item['id']]);
        }
        
        return ['detail'=>$detail,'list'=>$list];
    }

    public function getConfigTabChildIdsByTabId($tabId){
        $menuList = $this->dao->getConfigTabAll([]);
        $ids = $this->getChildIdsByTabId($tabId,$menuList);
        $tabId!= -1 && $ids[] = (int) $tabId;
        return $ids;
    }


    public function getChildIdsByTabId($tabId,$menuList){
        $ids = [];
        foreach ($menuList as $key => $value) {
            if( $value['pid'] == $tabId ){
                $ids[] = $value['id'];
                $ids = array_merge($ids,$this->getChildIdsByTabId($value['id'],$menuList));
            }
        }
        return $ids;
    }
}
